package xyz.xiangyushui.controller.admin.authorization;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.xiangyushui.dao.employee.EmployeeDao;
import xyz.xiangyushui.daoFactory.user.UserDaoFactory;
import xyz.xiangyushui.javaBean.user.Role;
import xyz.xiangyushui.javaBean.user.User;

/**
 * Servlet implementation class Authorization
 */
@WebServlet("/admin/authorization")
public class Authorization extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserDaoFactory f;
	private EmployeeDao ed;
	private final String emptyWarning = "Incomplete form!";
	private final String userExist = "The userName already exists!";
	private final String successMsg="employee successfully created!";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Authorization() {
        super();
        f = new UserDaoFactory();
        ed=new EmployeeDao();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		System.out.println("user:"+userName);
		String type = request.getParameter("type");
		System.out.println("type:"+type);
		String msg = validate(userName, password, type);
		System.out.println(msg);
		
		if (msg.equals(successMsg)) {
			User u = new User();
			u.setName(userName);
			u.setPwd(password);
			Role role=type.equals("leader")? Role.employeeLeader:Role.employee;
			u.setRole(role);
			f.getUserDao().add(u);
			//add employee
			ed.addEmployee(u.getName());
			
			request.setAttribute("successMsg", msg);
			request.getRequestDispatcher("/admin").forward(request, response);
		} else {
			request.setAttribute("failedMsg", msg);
			request.getRequestDispatcher("/admin").forward(request, response);
		}
	}
	
	private String validate(String userName, String pwd, String type) {
		String result = successMsg;
		if ("".equals(userName) || "".equals(pwd) || "".equals(type)||type==null) {
			result = emptyWarning;
		}  else {
			User u = new User();
			u.setName(userName);
			if (f.getUserDao().exists(u)) {
				result = userExist;
			}
		}
		return result;
	}

}
